package service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import common.impl.exception.ServiceException;
import dao.interf.IUserDAO;
import dao.interf.IWchatYunDAO;
import dao.pojo.User;
import dao.pojo.WchatYun;
import service.interf.IWchatYun;

public class WchatYunImpl extends BaseDataServiceImpl implements IWchatYun {

	private IWchatYunDAO wchatYunDao;
	private IUserDAO userDao;

	public void setWchatYunDao(IWchatYunDAO wchatYunDao) {
		this.wchatYunDao = wchatYunDao;
	}
	
	public void setUserDao(IUserDAO userDao) {
		this.userDao = userDao;
	}

	public String bind(String wchatId, String yunId) throws Exception {
		
		System.out.println("wchatId = " + wchatId);
		System.out.println("yunId = " + yunId);

		if (StringUtils.isEmpty(wchatId) || StringUtils.isEmpty(yunId)) {
			throw new ServiceException("系统错误，请重试");
		}
		
		List<User> userList = userDao.findByPropertiesRule(new String[] { "userName" }, new Object[] { yunId },
				null, null, 0, 1);
		if(null == userList || userList.isEmpty()) {
			throw new ServiceException("帐号不存在，请输入正确的帐号");
		}

		List<WchatYun> list = wchatYunDao.findByPropertiesRule(new String[] { "wchatId" }, new Object[] { wchatId },
				null, null, 0, 1);
		System.out.println("list.isEmpty() = " + list.isEmpty());
		WchatYun wchatYun = null;
		if (null != list && !list.isEmpty()) {
			wchatYun = list.get(0);
			wchatYun.setYunId(yunId);
			wchatYunDao.update(wchatYun);
		} else {
			wchatYun = new WchatYun();
			wchatYun.setWchatId(wchatId);
			wchatYun.setYunId(yunId);
			wchatYunDao.save(wchatYun);
		}
		System.out.println("成功");
		return "1";
	}

}
